import os
import sys

from django.core.wsgi import get_wsgi_application
from twisted.web import server
from twisted.web.wsgi import WSGIResource
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
from twisted.application import service, strports

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(ROOT_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'haohuo.settings')
os.environ.setdefault('HAOHUO_PORT', '8080')
os.environ.setdefault('HAOHUO_TITLE', '好活资产管理系统')
application = get_wsgi_application()

# Create and start a thread pool
wsgiThreadPool = ThreadPool()
wsgiThreadPool.start()

# ensuring that it will be stopped when the reactor shuts down
reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)


# Create the WSGI resource
wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, application)

# Hooks for twisted
application = service.Application(os.environ["HAOHUO_TITLE"])
server = strports.service(f'tcp:{os.environ["HAOHUO_PORT"]}', server.Site(wsgiAppAsResource))
server.setServiceParent(application)
